package servlet;

import entity.Product;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 */
@WebServlet("*.product")
public class ProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        switch (path) {
            case "/findAll.product":
                findAll(request, response);
                break;
            case "/findById.product":
                findById(request, response);
                break;
            default:
                System.out.println("请求不存在");
                break;
        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        List<Product> products = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                products.add(product);
            }
            request.setAttribute("products", products);
//            request.getRequestDispatcher("/jsp/list.jsp").forward(request, response);
            request.getRequestDispatcher("/jquery/list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        Product product = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
//                String jsonString = "{'id':" + product.getId() + ",'name':'" + product.getName() + "','price':" + product.getPrice() + "}";
                // 将一个Java对象转换成JSON对象
                JSONObject jsonObject = JSONObject.fromObject(product);
                // 将JSON对象转换成JSON格式的字符串
                String jsonString = jsonObject.toString();
                out.println(jsonString);
                // 对于集合使用JSONArray
//                JSONArray.fromObject(obj)
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
